package attend.Interceptor;

import static org.apache.struts2.StrutsStatics.HTTP_REQUEST;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import attend.UserContainer.User;
import attend.UserContainer.UserAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor {

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	public String intercept(ActionInvocation invocation) throws Exception
	{
		ActionContext 	context 	= 	invocation.getInvocationContext();
		Map 			session 	= 	context.getSession();
		
		User 						user 		= 	(User)session.get("user");
		//HashMap<String, String>		empInfo		=	(HashMap<String, String>)session.get("empInfo");
		HashMap<String, String>		empInfo		=	user.getEmpInfo();
		HashMap<String, String>[]	menu		=	(HashMap<String, String>[])session.get("menu");
		
		if(session == null || user == null || empInfo == null || menu == null || empInfo.size() < 1) {
			
			HttpServletRequest 	request 		= 	(HttpServletRequest)context.get(HTTP_REQUEST);
			String 				queryString 	= 	request.getQueryString();
			String 				currentURL 		= 	request.getServletPath() + (queryString != null ?"?" + queryString : "");
			
			request.setAttribute("url", currentURL);
			
			return "sessionfail";
		}
		
		Object  action = invocation.getAction();
		
		if(action instanceof UserAware){
			((UserAware)action).setUser(user);
		}
		
		return invocation.invoke();
	}
}
